<?php


namespace App\Common\Services;

use App\Common\Library\DES;
use App\Common\Models\SysEmailTaskModel;
use App\Services\CommonBaseService;
use App\Web\Facades\SysGlobalConfigFacade;
use Illuminate\Support\Facades\Mail;

class SysEmailTaskService extends CommonBaseService
{

    const DES_KEY = '1dgDG2ksghw';

    const SYS_MAIL_BOX = 'cXdWWktRNno0eitSL1Q1LzVKalRnUUlleTdESzZ5S2NDdW89OmZhY3A3WjNza0x6YmdJb0U0djlCR3c9PQ==';

    /**
     * SysEmailTaskService constructor.
     * @param SysEmailTaskModel $model
     */
    public function __construct(SysEmailTaskModel $model)
    {
        $this->model = $model;
    }

    /**
     * 批量添加短信任务
     * @param array $taskList
     * @return bool
     */
    public function addAllEmailTask(array $taskList)
    {
        $insertList = [];
        foreach ($taskList as $task) {
            if (!$task->toEmail || !strpos($task->toEmail, '@') || strlen($task->toEmail) > 30) {
                continue;
            }
            $insertList[] = [
                'relative_id' => $task->relativeId ?: 0,
                'relative_table' => $task->relativeTable ?: '',
                'template' => $task->template,
                'to_email' => $task->toEmail,
                'subject' => $task->subject,
                'content' => json_encode($task->templateData, JSON_UNESCAPED_UNICODE),
                'plan_time' => $task->planTime ?: nowTime()
            ];
        }
        return $this->model->insertAll($insertList);
    }

    /**
     * 添加邮件发送任务
     * @param \App\Common\Transmit\SysEmailTask $task
     * @return int
     */
    public function addEmailTask(\App\Common\Transmit\SysEmailTask $task)
    {
        $toEmails = explode(",", $task->toEmail);
        if (count($toEmails) > 1) {
            foreach ($toEmails as $val) {
                if (!strpos($val, '@') || strlen($val) > 30) {
                    return 0;
                }
            }
        } elseif (!$task->toEmail || !strpos($task->toEmail, '@') || strlen($task->toEmail) > 30) {
            return 0;
        }
        $data = [
            'relative_id' => $task->relativeId ?: 0,
            'relative_table' => $task->relativeTable ?: '',
            'template' => $task->template,
            'to_email' => $task->toEmail,
            'subject' => $task->subject,
            'content' => json_encode($task->templateData, JSON_UNESCAPED_UNICODE),
            'plan_time' => $task->planTime ?: nowTime()
        ];
        return $this->model->insertData($data);
    }

    /**
     * 发送队列
     */
    public function send()
    {
        $globalData = SysGlobalConfigFacade::getGlobalConfig([]);
        $globalData = mapByKey($globalData, 'global_key');
        if (empty($globalData['FORM_RECEIVE_MAIL']['value'])) { // 插入数据成功，并且有邮箱。发送邮件
            return;
        }
        $sysDesKey = config('mail.des_key');
        $sysMailBox = config('mail.sys_mail_box');
        if (empty($sysDesKey)) {
            $sysDesKey = self::DES_KEY;
        }
        if (empty($sysMailBox)) {
            $sysMailBox = self::SYS_MAIL_BOX;
        }
        $mailPwd = empty($globalData['FORM_RECEIVE_MAIL']['value']['mail_pwd']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['mail_pwd'];
        $mailUser = empty($globalData['FORM_RECEIVE_MAIL']['value']['mail_user']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['mail_user'];
        $smtpHost = empty($globalData['FORM_RECEIVE_MAIL']['value']['smtp_host']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['smtp_host'];
        $smtpPort = empty($globalData['FORM_RECEIVE_MAIL']['value']['smtp_port']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['smtp_port'];
        if (empty($mailPwd) || empty($mailUser) || empty($smtpHost) || empty($smtpPort)) {
            return;
        }

        $getter = new DES($sysDesKey);
        if ($mailUser == $getter->decrypt($sysMailBox)) {
            $mailPwd = $getter->decrypt($mailPwd);
        }
        $list = $this->model->getSendEmailList(100);
        foreach ($list as $task) {
            $task = (array) $task;
            $toEmails = explode(",", $task['to_email']);
            try {
                $mailSwift = Mail::getSwiftMailer();
                $mailgunTransport = $mailSwift->getTransport();
                $mailgunTransport->setUsername($mailUser);
                $mailgunTransport->setPassword($mailPwd);
                $mailgunTransport->setHost($smtpHost);
                $mailgunTransport->setPort($smtpPort);
                if ($smtpPort == 465) {
                    $mailgunTransport->setEncryption('ssl');
                } else {
                    $mailgunTransport->setEncryption('tls');
                }
                $title = $task['subject'] ?? '';
                foreach ($toEmails as $mail) {
                    $ret = Mail::send($task['template'], json_decode($task['content'], true), function ($message) use ($mail, $title, $mailUser) {
                        $message->from($mailUser, $mailUser);
                        $message->to($mail)->subject($title);
                    });
                }
            } catch (\Exception $e) {
                \Log::info($e->getMessage());
                $this->model->updateData([
                    'id' => $task['id'],
                    'send_error' => $e->getMessage(),
                    'send_status' => SysEmailTaskModel::SEND_STATUS_FAILED
                ]);
                continue;
            }
            //$failures = Mail::failures();
            if ($ret === true) {
                $this->model->updateData([
                    'id' => $task['id'],
                    'send_time' => nowTime(),
                    'send_status' => SysEmailTaskModel::SEND_STATUS_COMPLETED
                ]);
            } else {
                $this->model->updateData([
                    'id' => $task['id'],
                    'send_error' => $ret,
                    'send_status' => SysEmailTaskModel::SEND_STATUS_FAILED
                ]);
            }
        }
    }
}
